package demo1;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;


/**
 * @基本功能:
 * @program:Demo01
 * @author: 闫哥
 * @create:2024-01-08 16:15:32
 **/
public class Test02_jdbc {

    Connection connection ;
    @Before
    public void init() throws Exception {
        System.out.println("所有test方法执行前，必须先执行我");
        Class.forName("com.mysql.jdbc.Driver"); // 可以不写
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/text01",
                "root",
                "123456");
    }

    @After
    public void destory() throws Exception {
        System.out.println("所有test方法执行后，必须执行我");
        connection.close();
    }


    // 注解   演示新增
    @Test
    public void test01() throws Exception {


        // 因为是主键自增  null
        String sql = "insert into student values(null,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"张三丰");
        preparedStatement.setString(2,"武汉");
        preparedStatement.setInt(3,22);

        preparedStatement.execute();
        preparedStatement.close();

        // 因为是自动提交，所以不需要写提交这句话
        //connection.commit();
    }

   /* @Test  // 修改数据
    public void testUpdate() throws Exception{
        String sql = "update student set name='宝总' where id = ? ";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,4);
        preparedStatement.execute();

        preparedStatement.close();
    }

    @Test
    public void testDel() throws Exception{
        String sql = "delete from student where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,5);
        preparedStatement.execute();
        preparedStatement.close();
    }

    @Test
    public void  testSelect() throws Exception{
        String sql ="select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String birthday = resultSet.getString("birthday");
            System.out.println(id+","+name+","+birthday);
        }

        // 记得用完之后需要关闭，否则，将来会内存溢出的
        resultSet.close();
        preparedStatement.close();
    }*/

}
